import { defineStore } from "pinia";
import { computed, ref, watch } from "vue";
import { apiGetDepartment, apiGetGiveList, apiSetGiveList } from "../../api/clue/clue";
import { ElMessage } from "element-plus";

export const useClueStore = defineStore("clue", () => {
    // 分配的弹窗
    // 分配弹窗开关
    const distributeFlag = ref(false)
    // 存储归属部门数据
    const distributeList = ref([])
    const assignId = ref(null)
    // 获取分配里归属部门信息 // 点击分配
    const distributeFn = async (id) => {
        const { data } = await apiGetDepartment()
        distributeList.value = data
        distributeFlag.value = true
        assignId.value = id
        console.log(distributeList.value)
    }
    // 获取归属部门id
    const distributeId = ref(null)
    const giveList = ref(null)

    watch(distributeId, async (newVal) => {
        if (newVal) {
            const { data } = await apiGetGiveList(newVal)
            giveList.value = data
        }
    })

    // 用于确认分配参数
    const giveListParams = ref(null)
    const distributeParams = computed(() => {
        const arr = giveList.value.find(item => item.deptId = giveListParams.value)
        const params = {
            assignId: assignId.value,
            departmentId: arr.dept.deptId,
            deptId: arr.deptId,
            nickName: arr.nickName,
            type: 0,
            userId: arr.userId,
            userName: arr.userName
        }
        return params
    })
    // 分配线索确认
    const aaa = ref(1)
    const distributeConfirmFn = async () => {
        try {
            await apiSetGiveList(distributeParams.value)
            ElMessage.success('线索分配成功')
            distributeFlag.value = false
            aaa.value += 1
        }catch(err) {}
    }



    // 暴露出去
    return {
        distributeFlag,
        distributeList,
        distributeId,
        giveList,
        giveListParams,
        aaa,
        distributeFn,
        distributeConfirmFn
    }
})
